<template>
  <div class="newschedule-container" @click.stop="()=>{}">
    <Dialogdrawerdefect
      :ddtvisible.sync="tempVisible"
      :title="tempTitle"
      size="700px"
      :modal="true"
    >
      <div class="nsc-wrap" v-loading="loading">
        <div class="nsc-h">
          <el-form
            ref="formdata"
            :model="formdata"
            @submit.native.prevent
            label-width="100px"
            class="ky-form-inline ky-form-inline-sm">
            <el-form-item label="星期">
              <el-select ref="week" size="mini" v-model="formdata.week" multiple placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in weekOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时间">
              <el-input v-model="mmm" style="position: fixed; left: 1000000px;top:0;height: 1px;opacity: 0;"></el-input>
              <el-time-select
                ref="timeselect_start"
                placeholder="起始时间"
                v-model="formdata.beginTime"
                :picker-options="startTimePickerOption">
              </el-time-select>
              <el-time-select
                ref="timeselect_end"
                placeholder="结束时间"
                v-model="formdata.endTime"
                :picker-options="endTimePickerOption">
              </el-time-select>
            </el-form-item>
            <el-form-item label="时段区间">
              <el-radio-group v-model="formdata.timeInterval" size="mini" style="margin-top: 0;">
                <el-radio-button
                  v-for="item in timeIntervalOptions"
                  :key="item.value"
                  :label="item.value">{{item.label}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="号源数">
              <el-input ref="checkNum" v-model="formdata.checkNum" @keyup.native="validNumber('checkNum')" placeholder="请输入" maxlength="4"></el-input>
            </el-form-item>
            <el-form-item label="预留">
              <div slot="label">预留
                <el-tooltip class="item" effect="dark" content="预留号只允许前台登记用，临床预约或移动预约等不能使用会过滤掉！" placement="top-end">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
              <el-input ref="reserveNum" v-model="formdata.reserveNum" @keyup.native="validNumber('reserveNum')" placeholder="请输入" maxlength="4"></el-input>
            </el-form-item>
            <el-form-item label="追加">
              <el-input ref="addNum" v-model="formdata.addNum" @keyup.native="validNumber('addNum')" placeholder="请输入" maxlength="4"></el-input>
            </el-form-item>
            <el-form-item>
              <div slot="label">起始号码
                <el-tooltip class="item" effect="dark" content="起始号码如果比同班次前面的号源小，会自动计算衔接于前面的号源数！" placement="top-start">
                  <i class="el-icon-warning"></i>
                </el-tooltip>
              </div>
              <el-input ref="initialNum" v-model="formdata.initialNum" @keyup.native="validNumber('initialNum')" placeholder="请输入" maxlength="4"></el-input>
            </el-form-item>
            <el-form-item label="时段状态" v-if="templateType === 'schedule'">
              <el-select size="mini" v-model="formdata.appointmentStatus" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in appointmentStatusOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" v-if="templateType === 'template'">
              <el-switch
                style="margin-top: 8px;"
                v-model="formdata.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="停用">
              </el-switch>
              <!-- <el-select size="mini" v-model="formdata.status" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in statusOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select> -->
            </el-form-item>
            <el-form-item label="颜色:">
              <public-input-color-picker
                :value="formdata.color"
                :show-input="false"
                placeholder="请选择颜色"
                @change="(val)=>{formdata.color=val}"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="ky-divider"><el-divider></el-divider></div>
        <div class="nsc-m" v-show="tempVisible">
          <div class="nsc-m-tit">时段限制条件：</div>
          <ruleTemplate ref="ruleTemplate" :hospital-code="hospitalCode" :dep="dep"></ruleTemplate>
        </div>
        <div class="nsc-footer">
          <el-button size="small" @click="close">返回</el-button>
          <el-button size="small" type="primary" @click="save">确认设置</el-button>
        </div>
      </div>
    </Dialogdrawerdefect>
  </div>
</template>

<script>
import Dialogdrawerdefect from '@/components/dialogbox/dialogDrawerDefect'
import publicInputColorPicker from '@/components/color-picker/index'
import ruleTemplate from './ruleTemplate'
import { Options } from '@/utils/constant'
const _formdata = {
  id: 0,
  week: [], // 星期
  beginTime: '',
  endTime: '',
  timeInterval: '1',
  addNum: '0', // 追加
  reserveNum: '0', // 预留号码
  recordCode: '', // 模板标题
  templateName: '', // 添加到参数模板的模板标题
  initialNum: 1, // 初始号码
  startNum: 1, // 初始号码
  checkNum: 20, // 检查数量
  appointmentFilters: [], // 过来规则
  channel: [],
  check: [],
  status: '启用', // 状态
  color: '', // 颜色
  appointmentStatus: '计划排班'
}
export default {
  inject: ['tempListUpdate'],
  props: {
    tempTitle: {
      type: String,
      default: ''
    },
    templateType: {
      type: String,
      default: 'schedule' // schedule、template
    }
  },
  components: {
    ruleTemplate,
    Dialogdrawerdefect,
    publicInputColorPicker
  },
  data() {
    return {
      appoContinuation: false,
      loading: false,
      tempVisible: false,
      stfIsAdd: true, // false 编辑，默认 true 新增
      mmm: '', // 所在输入框，解决模态框打开是获取焦点的bug
      stfStatus: 'schedule', // 判断弹框模板使用的对象，schedule 排班管理，template 模板管理
      // 设置时间选项参数
      minMaxNum: null,
      stepTime: window.g.DEFAULTSTEPTIME || '00:30',
      startTime: '08:00',
      endTime: '12:00',
      formdata: {
        ..._formdata
      },
      appointmentStatusOptions: Options.appointmentStatusOptions,
      statusOptions: ['启用', '停用'],
      weekOptions: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      timeIntervalOptions: [
        { label: '30分钟', value: '1' },
        { label: '1小时', value: '2' }
      ],
      // 检查项目
      hospitalCode: '',
      dep: '',

      // 模板
      checkroom: [],
      tempObj: null,
      // 新增快捷参数模板
      dialogVisibleTemp: false,
      // 操作日志
      appoPeriodLogDlg: false,
      appoLogId: null
    }
  },
  computed: {
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    ISUSE_DEFAULTSTEPTIME() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.ISUSE_DEFAULTSTEPTIME) || window.g.ISUSE_DEFAULTSTEPTIME || false
    },
    startTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        maxTime: this.formdata.endTime
      }
    },
    endTimePickerOption() {
      return {
        start: this.startTime,
        step: this.stepTime,
        end: this.endTime,
        minTime: this.formdata.beginTime
      }
    }
  },
  methods: {
    async init(data) {
      const { room } = data
      this.tempVisible = true
      this.tempObj = null

      let appConfig = this.$store.state.settings.appConfig
      if (this.ISUSE_DEFAULTSTEPTIME) {
        this.stepTime = (appConfig && appConfig.baseConfig && appConfig.baseConfig.DEFAULTSTEPTIME) || window.g.DEFAULTSTEPTIME || '00:30'
      }

      this.startTime = '00:00'
      this.endTime = '24:00'
      this.checkroom = [...room]
      this.hospitalCode = room.length > 0 ? room[0] : ''
      this.dep = room.length > 0 ? room[2] : ''
      this.$nextTick(() => {
        // this.$refs.templateList && this.$refs.templateList.init(this.checkroom)
        this.$refs.ruleTemplate && this.$refs.ruleTemplate.init(this.formdata)
      })
    },

    // 保存
    async save() {
      if (this.validForm()) {
        let ruleParams = await this.$refs.ruleTemplate.getRuleData()
        ruleParams = JSON.parse(ruleParams)

        const resAppo = []
        const st = this.formdata.beginTime
        const et = this.formdata.endTime
        const step = this.formdata.timeInterval * 30
        const stn = st.split(':')[0] * 60 + st.split(':')[1] * 1
        const etn = et.split(':')[0] * 60 + et.split(':')[1] * 1
        let stnr = stn
        const getNumberToTimeFormat = (num) => {
          let h = Math.floor(num / 60)
          let s = Math.floor(num % 60)
          h = h < 10 ? '0' + h : h
          s = s > 0 ? s : '00'
          return h + ':' + s
        }
        let initialNum = this.formdata.initialNum

        const runSet = (stime) => {
          const _obj = JSON.parse(JSON.stringify({ ...this.formdata }))
          _obj.status = _obj.status ? '启用' : '停用'
          _obj.initialNum = initialNum
          _obj.appointmentFilters = [...ruleParams.appointmentFilters]
          const etime = stime + step
          if (etime <= etn) {
            _obj.beginTime = getNumberToTimeFormat(stime)
            _obj.endTime = getNumberToTimeFormat(etime)
            resAppo.push(_obj)
            initialNum = initialNum + _obj.checkNum
            runSet(etime)
          } else if (etn > stime) {
            _obj.beginTime = getNumberToTimeFormat(stime)
            _obj.endTime = getNumberToTimeFormat(etn)
            resAppo.push(_obj)
          }
        }
        runSet(stnr)
        const appoRes = []
        this.formdata.week.forEach(item => {
          const appoWeekData = []
          resAppo.forEach(r => {
            const rs = { ...r }
            rs.week = item
            appoWeekData.push(rs)
          })
          appoRes.push(appoWeekData)
        })
        this.$emit('addScheduleTempSave', appoRes)
        // console.log('resAppo', resAppo)
      }
    },

    // 必填选项验证
    validForm() {
      if (!this.formdata.week.length) {
        this.$message.warning('请选择星期！')
        this.$refs.week.focus()
        return false
      } else if (!this.formdata.beginTime) {
        this.$message.warning('请选择开始时间！')
        this.$refs.timeselect_start.focus()
        return false
      } else if (!this.formdata.endTime) {
        this.$message.warning('请选择结束时间！')
        this.$refs.timeselect_end.focus()
        return false
      } else if (!this.formdata.checkNum && this.formdata.checkNum !== 0) {
        this.$message.warning('请输入号源数量！')
        this.$refs.checkNum.focus()
        return false
      } else if (!this.formdata.reserveNum && this.formdata.reserveNum !== 0) {
        this.$message.warning('请输入预留数量！')
        this.$refs.reserveNum.focus()
        return false
      } else if (this.formdata.initialNum < this.formdata.startNum) {
        this.$message.warning(`初始号码不能小于${this.formdata.startNum}（时令班次设置的起始号码）！`)
        this.$refs.initialNum.focus()
        return false
      }
      return true
    },
    // 数据仅可输入数字判断
    validNumber(keyVal) {
      this.formdata[keyVal] = this.formdata[keyVal] ? this.formdata[keyVal].replace(/[^\d]/g, '') : this.formdata[keyVal]
    },

    // 退出
    close() {
      this.tempVisible = false
    },

    // 模板选择
    checkedTemplate(temObj) {
      this.tempObj = temObj
      // console.log('checkedTemplate:====', this.tempObj)
      this.$refs.ruleTemplate && this.$refs.ruleTemplate.resetInit(this.tempObj)
    },
    // 判断是否位24点，如果24点，则转为 23：59
    getEndTime(time) {
      if (!time) return ''
      const t = time.split(':')
      return t[0] * 1 === 24 ? '23:59' : time
    },
    getEndTimeM(time) {
      return time === '23:59' ? '24:00' : time
    }
  }
}
</script>

<style lang="scss" scoped>
.nsc-wrap{
  height: 100%;
  display: flex;
  flex-direction: column;
  // min-width: 600px;
  padding: 0 20px;
  /deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
    width: 120px;
  }
  /deep/ .el-form-item__label{
    font-weight: 500;
  }
  .nsc-m{
    padding:0px 0 54px;
    flex: 1;
    position: relative;
    .nsc-m-tit{
      font-size: 14px;
      font-weight: bold;
      padding: 4px 0;
    }
  }
  .nsc-footer{
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    text-align: right;
    padding: 10px 20px;
    border-top: solid 1px #DCDFE6;
    background-color: #fff;
  }
}
.sche_navs{
  position: absolute;
  top: 15px;
  right: 15px;
  cursor: pointer;
  user-select: none;
  .btn:hover{
    color: #00C0EF
  }
}
</style>
